package org.shan.security.oaserver.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore;

/**
 * Created by amanda.shan on 2019/3/10.
 */
@Configuration
@EnableAuthorizationServer  // 添加一个配置类即可
public class MyAuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    UserDetailsService userDetailsService;

    /**
     * 配置客户端详情服务
     * 客户端详细信息在这里进行初始化，你能够把客户端详情信息写死在这里或者是通过数据库来存储调取详情信息
     *
     * @param clients
     * @throws Exception
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                .withClient("client1")//用于标识用户ID
                .authorizedGrantTypes("authorization_code","refresh_token", "password")//授权方式
                .scopes("all")//授权范围
                .secret(PasswordEncoderFactories.createDelegatingPasswordEncoder().encode("123456"));//客户端安全码,secret密码配置从 Spring Security 5.0开始必须以 {bcrypt}+加密后的密码 这种格式填写;

    }


    /**
     * 用来配置令牌端点(Token Endpoint)的安全约束.
     *
     * @param security
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security
                // tokenKeyAccess对应的url是 /oauth/token_key
                // checkTokenAccess对应的url是 /oauth/check_token
                // 配置访问上面两个url的时候是否需要认证
                .tokenKeyAccess("permitAll()")
                .checkTokenAccess("isAuthenticated()")
                // 配置client认证是表单还是basic 加啦下面这个就是表单认证
                .allowFormAuthenticationForClients()
                // 设置 client密码的加密方式
//                .passwordEncoder(new PasswordEncoder() {
//                    @Override
//                    public String encode(CharSequence rawPassword) {
//                        return rawPassword.toString();
//                    }
//
//                    @Override
//                    public boolean matches(CharSequence rawPassword, String encodedPassword) {
//                        return rawPassword.equals(encodedPassword);
//                    }
//                })
        ;
    }

    /**
     * 用来配置授权（authorization）以及令牌（token）的访问端点和令牌服务(token services)
     *
     * @param endpoints
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints
                // 设置 authenticationManager 这个主要是用来验证user用户的账号密码
                // 主要是密码模式的时候会用到
                .authenticationManager(authenticationManager)
                // token存储的方式
                .tokenStore(tokenStore())
                // 设置用来获取认证用户的 UserDetails
                .userDetailsService(userDetailsService)

        ;
    }

    @Bean
    public TokenStore tokenStore() {
        return new InMemoryTokenStore();
    }

}
